package com.example.teaching_server.entity;

import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.*;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 学期实体类
 */
@Getter
@Setter
@ToString
@EqualsAndHashCode(of = "termId")
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "terms", indexes = {
        @Index(name = "idx_term_name", columnList = "termName"),
        @Index(name = "idx_term_current", columnList = "isCurrent"),
        @Index(name = "idx_term_dates", columnList = "startDate, endDate")
})
public class TermEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long termId;

    @NotBlank(message = "学期名称不能为空")
    @Size(max = 50, message = "学期名称长度不能超过50个字符")
    @Column(nullable = false, unique = true, length = 50)
    private String termName;

    @NotNull(message = "开始日期不能为空")
    @Column(nullable = false)
    private LocalDate startDate;

    @NotNull(message = "结束日期不能为空")
    @Column(nullable = false)
    private LocalDate endDate;

    @Column(nullable = false)
    private Boolean isCurrent = false;

    /**
     * 兼容性方法：getId() 和 getTermId() 返回相同值
     */
    public Long getId() {
        return termId;
    }

    public void setId(Long id) {
        this.termId = id;
    }

    /**
     * 验证学期是否有效
     */
    public boolean isValid() {
        return termName != null && !termName.trim().isEmpty() &&
                startDate != null && endDate != null &&
                startDate.isBefore(endDate);
    }

    /**
     * 检查日期是否在学期范围内
     */
    public boolean containsDate(LocalDate date) {
        return date != null &&
                !date.isBefore(startDate) &&
                !date.isAfter(endDate);
    }

    /**
     * 学期是否正在进行中
     */
    public boolean isInProgress() {
        LocalDate today = LocalDate.now();
        return containsDate(today);
    }

    /**
     * 获取学期时长（天数）
     */
    public long getDurationInDays() {
        return java.time.temporal.ChronoUnit.DAYS.between(startDate, endDate) + 1;
    }
}
